<?php
/**
 * @author fld 2021-06-14
 * @desc 登陆控制类
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\AdminBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Service\Admin\LoginService;
use App\Service\Admin\AdminLoginlogService;

class LoginController extends AdminBaseController
{
    /**
     * @author fld 2021-06-14
     * @desc 登陆页面
     * @param Request $request
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function login(Request $request){
        $request->session()->forget(['admin', 'role_menu_action']);
        return view('admin/login/login');
    }
    /**
     * @author fld 2021-06-14
     * @desc 登陆验证
     * @param Request $request
     */
    public function dologin(Request $request,LoginService $loginService,AdminLoginlogService $adminLoginlogService){
        $params = $request->all();
        $validator = Validator::make($params, [
            'username' => 'required',
            'password' => 'required',
            'captcha' => 'required|captcha',
        ],[
            'username.required' => '用户名不能为空',
            'password.required' => '密码不能为空',
            'captcha.required' => '验证码不能为空',
            'captcha.captcha' => '验证码错误，请重新输入',
        ]);
        $params['login_ip'] = $request->getClientIp();
        $log_data['username'] = $params['username'];
        $log_data['login_ip'] = $params['login_ip'];
        if($validator->fails()){
            $message = $validator->errors()->first();
            //保存登录日志
            $log_data['status'] = 0;
            $log_data['remark'] = $message;
            $adminLoginlogService->addAdminLoginLog($log_data);
            return $this->failed(1, ['message'=>$message]);
        }else{
            $login_result = $loginService->doLogin($params);
            if($login_result['code'] == 0){
                //保存登录日志
                $log_data['status'] = 1;
                $log_data['true_name'] = $login_result['true_name'];
                $adminLoginlogService->addAdminLoginLog($log_data);
                return $this->success(['url'=>url('admin/index')]);
            }else{
                //保存登录日志
                $log_data['status'] = 0;
                $log_data['remark'] = $login_result['message'];
                $adminLoginlogService->addAdminLoginLog($log_data);
                return $this->failed($login_result['code'], ['message'=>$login_result['message']]);
            }
        }
    }
    /**
     * @author fld 2021-06-14
     * @desc 退出登陆
     * @param Request $request
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
     */
    public function loginout(Request $request){
        $request->session()->flush();
        return redirect(url('admin/login'));
    }
}
